#include <QMessageBox>

#include "settingsdialog.h"
#include "ui_settingsdialog.h"

settingsDialog::~settingsDialog()
{
    delete m_ui;
}

void settingsDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

QString settingsDialog::getSettingsFolderPath()
{
    TCHAR szPath[MAX_PATH];
    QString path;

    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szPath );

    for ( uint i = 0; i < 260; i++)
    {
            if ( szPath[i] != 0 )
                    path += (char)szPath[i];
            else
                    break;
    }

    path.replace( "\\", "/" );
    path.append( "/Folder index/settings" );
    return path;
}

settingsDialog::settingsDialog(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::settingsDialog)
{
    m_ui->setupUi(this);
    initComboBoxes();

    connect( m_ui->fractionCombo, SIGNAL( currentIndexChanged ( int ) ),
             this, SLOT( numberFormatChanged() ) );
    connect( m_ui->groupSeparatorCombo, SIGNAL( currentIndexChanged ( int ) ),
             this, SLOT( numberFormatChanged() ) );
}

int settingsDialog::run_form( int mode, const QString& name )
{
    runMode = mode;
    m_ui->nameLine->setFocus();
    m_ui->nameLine->selectAll();

    if ( mode == 0 ) // new
    {
        m_ui->nameLine->setEnabled( true );
        openFileName = "";
        clearAll();
        saveFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(name);
    }
    else if ( mode == 1 ) // edit
    {
        m_ui->nameLine->setText( name );
        m_ui->nameLine->setEnabled( false );

        openFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(name);
        saveFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(name);
        getSettings();
    }
    else if ( mode == 2 ) // clone
    {
        m_ui->nameLine->setEnabled( true );
        openFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(name);
        getSettings();
        saveFileName = "";
    }
    return exec();
}

void settingsDialog::initComboBoxes()
{
    dates.clear();
    dateFormats.clear();
    times.clear();
    timeFormats.clear();

    QDate date( 2009, 12, 31 );
    dates.append( date.toString("dd.MM.yyyy") );
    dateFormats.append( "dd.MM.yyyy" );
    dates.append( date.toString("dd/MM/yyyy") );
    dateFormats.append( "dd/MM/yyyy" );
    dates.append( date.toString("yyyy-MM-dd") );
    dateFormats.append( "yyyy-MM-dd" );
    dates.append( date.toString("yyyy/MM/dd") );
    dateFormats.append( "yyyy/MM/dd" );

    m_ui->dateCombo->addItems( dates );

    QTime time( 15, 20, 45, 999 );
    times.append( time.toString("hh:mm:ss:zzz") );
    timeFormats.append( "hh:mm:ss:zzz" );
    times.append( time.toString("h:m:s A") );
    timeFormats.append( "dh:m:s A" );

    m_ui->timeCombo->addItems( times );
}

void settingsDialog::numberFormatChanged()
{
    QString number = "12^345~87";

    number.replace( "^", getGroupSeparator() );
    number.replace( "~", getFractionDel() );
    m_ui->formatLine->setText( number );
}

void settingsDialog::clearAll()
{
    m_ui->nameLine->clear();
    m_ui->separatorCombo->setCurrentIndex( 0 );
    m_ui->dateCombo->setCurrentIndex( 0 );
    m_ui->timeCombo->setCurrentIndex( 0 );
    m_ui->fractionCombo->setCurrentIndex( 0 );
    m_ui->groupSeparatorCombo->setCurrentIndex( 0 );

    m_ui->show_full_path->setChecked(false);
    m_ui->groupBox1->setChecked(true);
    m_ui->fileExtensionCombo->setCurrentIndex( 0 );
    m_ui->groupBox_2->setChecked(true);
    m_ui->fileSizeCombo->setCurrentIndex( 0 );
    m_ui->display_item_type->setChecked(false);
    m_ui->file_attributes->setChecked(false);
    m_ui->creation_date->setChecked(false);
    m_ui->owner->setChecked(false);
    m_ui->modification_date->setChecked(false);
    m_ui->md5_hash->setChecked(false);
    m_ui->last_access_date->setChecked(false);

    m_ui->rootCheck->setChecked(false);
    m_ui->fullRootPath->setChecked(false);
}

void settingsDialog::getSettings()
{
    if ( !QFile::exists( openFileName ) )
    {
        QMessageBox::critical( this, "Settings", "File doesn't exist!!!" );
        reject();
        return;
    }

    QFile file( openFileName );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
        QMessageBox::critical( this, "Settings", "Couldn't read file" );
        reject();
        return;
    }

    QDataStream in(&file);
    QStringList lines;
    in >> lines;

    if ( lines.size() == 0 )
    {
        QMessageBox::critical( this, "Settings", "Empty file" );
        reject();
        return;
    }

    for ( int i = 0; i < lines.size(); i++ )
    {
        QStringList paramList = lines.at(i).split('=', QString::SkipEmptyParts );
        if ( paramList.size() < 2 )
        {
            paramList.append("null");
            paramList.append("null");
        }

        if ( paramList.at(0) == "Separator" )
            m_ui->separatorCombo->setCurrentIndex(
                    m_ui->separatorCombo->findText( paramList.at(1), Qt::MatchExactly ) );
        if ( paramList.at(0) == "Date format" )
            m_ui->dateCombo->setCurrentIndex(
                    m_ui->dateCombo->findText( paramList.at(1), Qt::MatchExactly ) );
        if ( paramList.at(0) == "Time format" )
            m_ui->timeCombo->setCurrentIndex(
                    m_ui->timeCombo->findText( paramList.at(1), Qt::MatchExactly ) );
        if ( paramList.at(0) == "Fraction delimeter" )
            m_ui->fractionCombo->setCurrentIndex(
                    m_ui->fractionCombo->findText( paramList.at(1), Qt::MatchExactly ) );
        if ( paramList.at(0) == "Fraction separator" )
            m_ui->groupSeparatorCombo->setCurrentIndex(
                    m_ui->groupSeparatorCombo->findText( paramList.at(1), Qt::MatchExactly ) );
        numberFormatChanged();

        if ( paramList.at(0) == "Show full path" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->show_full_path->setChecked(true);
            else
                m_ui->show_full_path->setChecked(false);
        }
        if ( paramList.at(0) == "display file extension" )
        {
            m_ui->groupBox1->setChecked(true);
            m_ui->fileExtensionCombo->setCurrentIndex( m_ui->fileExtensionCombo->findText(paramList.at(1)) );
        }
        if ( paramList.at(0) == "file size" )
        {
            m_ui->groupBox_2->setChecked(true);
            m_ui->fileSizeCombo->setCurrentIndex( m_ui->fileSizeCombo->findText(paramList.at(1)) );
        }
        if ( paramList.at(0) == "Display item type" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->display_item_type->setChecked(true);
            else
                m_ui->display_item_type->setChecked(false);
        }
        if ( paramList.at(0) == "creation date" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->creation_date->setChecked(true);
            else
                m_ui->creation_date->setChecked(false);
        }
        if ( paramList.at(0) == "modification date" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->modification_date->setChecked(true);
            else
                m_ui->modification_date->setChecked(false);
        }
        if ( paramList.at(0) == "last access date" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->last_access_date->setChecked(true);
            else
                m_ui->last_access_date->setChecked(false);
        }
        if ( paramList.at(0) == "file attributes" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->file_attributes->setChecked(true);
            else
                m_ui->file_attributes->setChecked(false);
        }

        if ( paramList.at(0) == "owner" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->owner->setChecked(true);
            else
                m_ui->owner->setChecked(false);
        }
        if ( paramList.at(0) == "md5 hash" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->md5_hash->setChecked(true);
            else
                m_ui->md5_hash->setChecked(false);
        }

        if ( paramList.at(0) == "Root folder shown" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->rootCheck->setChecked(true);
            else
                m_ui->rootCheck->setChecked(false);
        }
        if ( paramList.at(0) == "Full root path show" )
        {
            if ( paramList.at(1) == "1" )
                m_ui->fullRootPath->setChecked(true);
            else
                m_ui->fullRootPath->setChecked(false);
        }
    }

    file.close();
}

void settingsDialog::getSettings( const QString& name )
{
    openFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(name);
    getSettings();
}

void settingsDialog::setSettings()
{
    QFile file( saveFileName );
    if ( !file.open( QIODevice::WriteOnly ) )
        return;

    QDataStream out(&file);
    QStringList strToFile;

    strToFile.append( QString("Separator=%1").arg(m_ui->separatorCombo->currentText() ) );
    strToFile.append( QString("Date format=%1").arg(m_ui->dateCombo->currentText() ) );
    strToFile.append( QString("Time format=%1").arg(m_ui->timeCombo->currentText() ) );
    strToFile.append( QString("Fraction delimeter=%1")
                      .arg(m_ui->fractionCombo->currentText() ) );
    strToFile.append( QString("Fraction separator=%1")
                      .arg(m_ui->groupSeparatorCombo->currentText() ) );

    if ( m_ui->show_full_path->isChecked() )
        strToFile.append("Show full path=1");
    else
        strToFile.append("Show full path=0");

    if ( m_ui->groupBox1->isChecked() )
        strToFile.append( QString("display file extension=%1").arg( m_ui->fileExtensionCombo->currentText()) );

    if ( m_ui->groupBox_2->isChecked() )
        strToFile.append( QString("file size=%1").arg( m_ui->fileSizeCombo->currentText()) );

    if ( m_ui->display_item_type->isChecked() )
        strToFile.append("Display item type=1");
    else
        strToFile.append("Display item type=0");

    if ( m_ui->creation_date->isChecked() )
        strToFile.append("creation date=1");
    else
        strToFile.append("creation date=0");

    if ( m_ui->modification_date->isChecked() )
        strToFile.append("modification date=1");
    else
        strToFile.append("modification date=0");

    if ( m_ui->last_access_date->isChecked() )
        strToFile.append("last access date=1");
    else
        strToFile.append("last access date=0");

    if ( m_ui->file_attributes->isChecked() )
        strToFile.append("file attributes=1");
    else
        strToFile.append("file attributes=0");

    if ( m_ui->owner->isChecked() )
        strToFile.append("owner=1");
    else
        strToFile.append("owner=0");

    if ( m_ui->md5_hash->isChecked() )
        strToFile.append("md5 hash=1");
    else
        strToFile.append("md5 hash=0");


    if ( m_ui->rootCheck->isChecked() )
        strToFile.append("Root folder shown=1");
    else
        strToFile.append("Root folder shown=0");

    if ( m_ui->fullRootPath->isChecked() )
        strToFile.append("Full root path show=1");
    else
        strToFile.append("Full root path show=0");

    out << strToFile;
    file.close();
}

void settingsDialog::on_resetButton_clicked()
{
    m_ui->separatorCombo->setCurrentIndex( 0 );
    m_ui->dateCombo->setCurrentIndex( 0 );
    m_ui->timeCombo->setCurrentIndex( 0 );
    m_ui->fractionCombo->setCurrentIndex( 0 );
    m_ui->groupSeparatorCombo->setCurrentIndex( 0 );

    m_ui->show_full_path->setChecked(false);
    m_ui->groupBox1->setChecked(true);
    m_ui->fileExtensionCombo->setCurrentIndex( 0 );
    m_ui->groupBox_2->setChecked(true);
    m_ui->fileSizeCombo->setCurrentIndex( 0 );
    m_ui->display_item_type->setChecked(true);
    m_ui->file_attributes->setChecked(false);
    m_ui->creation_date->setChecked(true);
    m_ui->owner->setChecked(true);
    m_ui->modification_date->setChecked(true);
    m_ui->md5_hash->setChecked(false);
    m_ui->last_access_date->setChecked(false);

    m_ui->rootCheck->setChecked(false);
    m_ui->fullRootPath->setChecked(false);
}

bool settingsDialog::checkName( const QString& name )
{
    if ( runMode != 1 ) // if clone or new
    {
        QDir dir( getSettingsFolderPath() );
        QStringList myList = dir.entryList( QStringList( QString("%1.lvm").arg(name)),
                                            QDir::NoDotAndDotDot|QDir::Files|
                                            QDir::NoSymLinks);
        if ( myList.count() > 0 )
        {
            QMessageBox::critical( this, "Error", "There is already mode with such name" );
            return false;
        }
    }

    return true;
}

void settingsDialog::on_okButton_clicked()
{
    if ( !m_ui->nameLine->text().isEmpty() )
    {
        QDir iniDir( getSettingsFolderPath() );
        if ( !iniDir.exists() )
            iniDir.mkpath( getSettingsFolderPath() );

        if ( checkName( m_ui->nameLine->text() ) )
        {
            saveFileName = getSettingsFolderPath() + QString("/%1.lvm").arg(m_ui->nameLine->text());
            setSettings();
            accept();
        }
    }
    else
        QMessageBox::critical( this, "Error", "You must specify view mode name" );
}

void settingsDialog::on_cancelButton_clicked()
{
    reject();
}

bool settingsDialog::showFullPath()
{ return m_ui->show_full_path->isChecked(); }

bool settingsDialog::displayFileExtension()
{ return m_ui->groupBox1->isChecked(); }

bool settingsDialog::attachToFilename()
{
    if ( m_ui->fileExtensionCombo->currentIndex() == 0 )
        return true;
    return false;
}

bool settingsDialog::displayItemType()
{ return m_ui->display_item_type->isChecked(); }

bool settingsDialog::displayFileSize()
{ return m_ui->groupBox_2->isChecked(); }

int settingsDialog::displayFileSizeType()
{
    // bytes
    return m_ui->fileSizeCombo->currentIndex()+1;
}

bool settingsDialog::creationDate()
{ return m_ui->creation_date->isChecked(); }

bool settingsDialog::modificationDate()
{ return m_ui->modification_date->isChecked(); }

bool settingsDialog::lastAccessDate()
{ return m_ui->last_access_date->isChecked(); }

bool settingsDialog::fileAttributes()
{ return m_ui->file_attributes->isChecked(); }

bool settingsDialog::owner()
{ return m_ui->owner->isChecked(); }

bool settingsDialog::md5Hash()
{ return m_ui->md5_hash->isChecked(); }

bool settingsDialog::rootFolderShow()
{ return m_ui->rootCheck->isChecked(); }

QString settingsDialog::getFractionDel()
{
    return m_ui->fractionCombo->currentText().left(1);
}

QString settingsDialog::getGroupSeparator()
{
    if ( m_ui->groupSeparatorCombo->currentText().isEmpty() )
        return QString::null;
    return m_ui->groupSeparatorCombo->currentText().left(1).replace("_", " ");
}

QString settingsDialog::getSeparator()
{
    return m_ui->separatorCombo->currentText();
}

QString settingsDialog::getDateFormat()
{
    return dateFormats.at( m_ui->dateCombo->currentIndex() );
}

QString settingsDialog::getTimeFormat()
{
    return timeFormats.at( m_ui->timeCombo->currentIndex() );
}

QString settingsDialog::getLastSaveFolder()
{
    QString retStr;

    QSettings settings("Folder index", "Settings");
    settings.beginGroup("Folders");
        retStr = settings.value("last_save_folder", "" ).toString();
    settings.endGroup();

    return retStr;
}

void settingsDialog::setLastSaveFolder( QString path )
{
    QSettings settings("Folder index", "Settings");
    settings.beginGroup("Folders");
        settings.setValue( "last_save_folder", path );
    settings.endGroup();
}

QString settingsDialog::getLastReadFolder()
{
    QString retStr;

    QSettings settings("Folder index", "Settings");
    settings.beginGroup("Folders");
        retStr = settings.value("last_read_folder", "" ).toString();
    settings.endGroup();

    return retStr;
}

void settingsDialog::setLastReadFolder( QString path )
{
    QSettings settings("Folder index", "Settings");
    settings.beginGroup("Folders");
        settings.setValue("last_read_folder", path );
    settings.endGroup();
}

void settingsDialog::on_rootCheck_stateChanged(int state)
{
    if ( state == 0 )
    {
        m_ui->fullRootPath->setEnabled( false );
        m_ui->fullRootPath->setChecked( false );
    }
    else if ( state == 2 )
        m_ui->fullRootPath->setEnabled( true );
}

bool settingsDialog::fullRootPathShow()
{
    return m_ui->fullRootPath->isChecked();
}

// ----------------------------------
void settingsDialog::exportCustomMode( const QString& modeName, const QString& filePath )
{
    if ( !modeName.isEmpty() )
    {
        getSettings(modeName);
        doExport( modeName, filePath );
    }
}

void settingsDialog::doExport( const QString& name, const QString& path )
{
    QFile file( path );
    if ( !file.open( QIODevice::WriteOnly ) )
        return;

    QTextStream out(&file);
    QString strToFile;

    strToFile.append( QString("Listing creator v. 1.0\n") );
    strToFile.append( QString("Name=%1\n").arg( name ) );
    strToFile.append( QString("Date format=%1\n").arg(m_ui->dateCombo->currentText() ) );
    strToFile.append( QString("Time format=%1\n").arg(m_ui->timeCombo->currentText() ) );
    strToFile.append( QString("Fraction delimeter=%1")
                      .arg(m_ui->fractionCombo->currentText() ) );
    strToFile.append( QString("Fraction separator=%1")
                      .arg(m_ui->groupSeparatorCombo->currentText() ) );

    if ( m_ui->show_full_path->isChecked() )
        strToFile.append("Show full path=1\n");
    else
        strToFile.append("Show full path=0\n");

    if ( m_ui->groupBox1->isChecked() )
        strToFile.append( QString("display file extension=%1\n").arg( m_ui->fileExtensionCombo->currentText()) );

    if ( m_ui->groupBox_2->isChecked() )
        strToFile.append( QString("file size=%1\n").arg( m_ui->fileSizeCombo->currentText()) );

    if ( m_ui->display_item_type->isChecked() )
        strToFile.append("Display item type=1\n");
    else
        strToFile.append("Display item type=0\n");

    if ( m_ui->creation_date->isChecked() )
        strToFile.append("creation date=1\n");
    else
        strToFile.append("creation date=0\n");

    if ( m_ui->modification_date->isChecked() )
        strToFile.append("modification date=1\n");
    else
        strToFile.append("modification date=0\n");

    if ( m_ui->last_access_date->isChecked() )
        strToFile.append("last access date=1\n");
    else
        strToFile.append("last access date=0\n");

    if ( m_ui->file_attributes->isChecked() )
        strToFile.append("file attributes=1\n");
    else
        strToFile.append("file attributes=0\n");

    if ( m_ui->owner->isChecked() )
        strToFile.append("owner=1\n");
    else
        strToFile.append("owner=0\n");

    if ( m_ui->md5_hash->isChecked() )
        strToFile.append("md5 hash=1\n");
    else
        strToFile.append("md5 hash=0\n");

    if ( m_ui->rootCheck->isChecked() )
        strToFile.append("Root folder shown=1\n");
    else
        strToFile.append("Root folder shown=0\n");

    if ( m_ui->fullRootPath->isChecked() )
        strToFile.append("Full root path show=1\n");
    else
        strToFile.append("Full root path show=0\n");

    out << strToFile;
    file.close();
}

bool settingsDialog::importCustomMode( const QString& path, QString name )
{
    if ( !path.isEmpty() )
    {
        QFile fileIn( path );
        if ( !fileIn.open( QIODevice::ReadOnly ) )
            return false;

        QTextStream in(&fileIn);
        // check format
        if ( in.readLine() != "Listing creator v. 1.0" )
        {
            QMessageBox::critical( this,
                                   "Error",
                                   "Chosen file has insupported format" );
            return false;
        }

        // check name
        QString importedPath = qApp->applicationDirPath() + QString("/settings/");
        QStringList names = in.readLine().split( "=", QString::SkipEmptyParts );
        if ( names.at(0).toLower() == "name" )
        {
            importedPath.append( QString( "%1.lvm" ).arg(names.at(1)) );
            name = names.at(1);
        }
        else
            return false;

        QFile fileOut( importedPath );
        if ( !fileOut.open( QIODevice::WriteOnly ) )
            return false;

        QDataStream out(&fileOut);
        QStringList importStrList;

        while (!in.atEnd())
            importStrList.append( in.readLine() );

        out << importStrList;

        fileIn.close();
        fileOut.close();
        return true;
    }
    return false;
}
